#include <QApplication>
#include <QtDebug>
#include "ui_operate_manager_02.h"

#include "file_process_02.h"
#include "track_process_02.h"
#include "../data_files/track_data_02.h"
//#include "../process_files/track_process_02.h"

Ui_operate_manager_02::Ui_operate_manager_02(QObject *parent)
    : QObject(parent)
    , file_process_(new File_process_02())
    , track_process_(new Track_process_02())
{
    init_connections();
}

Ui_operate_manager_02::~Ui_operate_manager_02()
{
    if ((nullptr != file_process_)
            && (file_process_->thread() == thread())) {
        delete file_process_;
        file_process_ = nullptr;
    }

    file_thread_.quit();
    file_thread_.wait();

    if ((nullptr != track_process_)
            && (thread() == track_process_->thread())) {
        delete track_process_;
        track_process_ = nullptr;
    }

    track_thread_.quit();
    track_thread_.wait();
}

void Ui_operate_manager_02::get_filter_conditions(QMap<QString, QVariant> *filter,
                                                  QList<Track_data_02 *> *list)
{
    if (nullptr == track_process_) {
        track_process_ = new Track_process_02();
    }

    start_file_thread(track_thread_, track_process_);

//    qDebug()<< "Ui_operate_manager_02::get_filter_conditions" << QThread::currentThreadId() << endl;

    emit si_send_track_to_process(filter, list);
}

void Ui_operate_manager_02::sl_open_files(QStringList file_name_list)
{
    start_file_thread(file_thread_, file_process_);

    emit si_open_file(file_name_list);
}

void Ui_operate_manager_02::sl_split_file_content(QStringList file_name_list)
{
    start_file_thread(file_thread_, file_process_);

    emit si_split_file_content(file_name_list);
}

void Ui_operate_manager_02::sl_exit_application()
{
    qApp->closeAllWindows();
}

void Ui_operate_manager_02::init_connections()
{
    connect(this, &Ui_operate_manager_02::si_open_file,
            file_process_, &File_process_02::sl_open_files);

    connect(this, &Ui_operate_manager_02::si_split_file_content,
            file_process_, &File_process_02::sl_split_file_data);

    // Send track data from File_process_02 to Track_data_table_model_02
    connect(file_process_, &File_process_02::si_send_track_to_model,
            this, &Ui_operate_manager_02::si_send_track_to_model);

    connect(track_process_, &Track_process_02::si_update_track_to_show,
            this, &Ui_operate_manager_02::si_updte_model_by_filter);

    connect(this, &Ui_operate_manager_02::si_send_track_to_process,
            track_process_, &Track_process_02::sl_filter_track_data);
}

void Ui_operate_manager_02::start_file_thread(QThread &thread, QObject *process)
{
    if ( !thread.isRunning()) {
        if (nullptr != process) {
            process->moveToThread(&thread);
            connect(&thread, &QThread::finished, process, &QObject::deleteLater);

            thread.start();
        }
    }
}
